package com.ray.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.ray.bean.CompanyBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DepartmentBean;
import com.ray.bean.DeviceBean;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.OrderBean;
import com.ray.bean.OrderBoLiangBean;
import com.ray.bean.OrderDeatilBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.OrderProcedureTemplateBean;
import com.ray.bean.PrintDetailBean;
import com.ray.bean.ProcedureBean;
import com.ray.bean.ProcessBean;
import com.ray.bean.ReportBean;
import com.ray.bean.TypeColorBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.bean.WorkshopProductionCycleBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.OrderProcedureTemplateMapper;
import com.ray.util.CreateIdUtil;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.StringUtil;

import net.sf.json.JSONArray;

@Service
public class OrderProcedureTemplateService {
	
	
	@Autowired
	OrderProcedureTemplateMapper orderProcedureTemplateMapper;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	OrderService orderService;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	CompanyService companyService;
	@Autowired
	PutOutServiceNew putOutServiceNew;
	@Autowired
	CompanyMaterialService companyMaterialService;
	@Autowired
	ApprovalService approvalService;

	//添加模板
	public void addTemplate(Map map) {
		String jsonArrayStr=map.get("procedureArray").toString();
		String uuid=StringUtil.getUUID();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String createTime = formatter.format(new Date());
		JSONArray jsonArray = JSONArray.fromObject(jsonArrayStr);//把String转换为 数组 
		List<ProcessBean> list= (List<ProcessBean>)JSONArray.toCollection(jsonArray, ProcessBean.class);
		for(int i=0;i<list.size();i++) {
			list.get(i).setId(StringUtil.getUUID());
		}
		map.put("procedureArray", list);
		map.put("uuid", uuid);
		map.put("createTime", createTime);
		String type=map.get("type").toString();
		//类型为创建创建新模板
		if(type.equals("create")) {
			orderProcedureTemplateMapper.insertTemplate(map);
		}
		//类型为添加将UUID设置模板id
		if(type.equals("add")) {
			map.put("uuid", map.get("tempId"));
		}
		orderProcedureTemplateMapper.insertTemplateProcedure(map);
	}

	//设置人员工序
	public void addUserProcedure(Map map) {
		String jsonArrayStr=map.get("procedureArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(jsonArrayStr);//把String转换为 数组 
		List<ProcessBean> list= (List<ProcessBean>)JSONArray.toCollection(jsonArray, ProcessBean.class);
		for(int i=0;i<list.size();i++) {
			list.get(i).setId(StringUtil.getUUID());
		}
		map.put("procedureArray", list);
		orderProcedureTemplateMapper.insertUserProcedure(map);
	}
	
	//设置订单工序
	public void addOrderProcedure(Map map) {
		orderProcedureTemplateMapper.removeOrderProcedure(map);
		String jsonArrayStr=map.get("procedureArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(jsonArrayStr);//把String转换为 数组 
		List<ProcessBean> list= (List<ProcessBean>)JSONArray.toCollection(jsonArray, ProcessBean.class);
		for(int i=0;i<list.size();i++) {
			list.get(i).setId(StringUtil.getUUID());
		}
		map.put("procedureList", list);
		orderProcedureTemplateMapper.addOrderProcedure(map);
	}
	
	/**
	 * 给订单赋予相同的工厂型号的工序
	 * @param orderId 系统编号
	 * @param company 公司
	 * @param factoryId 工厂型号
	 */
    public String  addOrderProcedureBySameOrder(String orderId,String company,String factoryId) {
    	if(factoryId==null || "".equals(factoryId) || orderId==null || "".equals(orderId) || company==null || "".equals(company)  ) {
    		return null;
    	}
    	Map map=new HashMap();
    	map.put("loginCompany", company);
    	map.put("orderId", orderId);
    	List<ProcessBean> orderProcess=orderProcedureTemplateMapper.getOrderProcess(map);
    	//如果这个订单没有设置过工序
    	if(orderProcess == null|| orderProcess.size() <=0) {
    		//查找该订单相同的工厂型号设置的工序
    		List<ProcessBean> list=orderProcedureTemplateMapper.getSameOrderId(company,factoryId);
    		//没有设置过不操作
    		if(list == null || list.size()<=0) {
    			return null;
    		}
    		for(int i=0;i<list.size();i++) {
    			list.get(i).setId(StringUtil.getUUID());
    		}
    		map.put("procedureList", list);
    		orderProcedureTemplateMapper.addOrderProcedure(map);
    	}
    	return null;
    }
	
	

    //通过模板为订单添加工序
	public void addOrderProcedureByTemp(Map map) throws ServiceException {
		String workshopIdArray=map.get("workshopIdArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(workshopIdArray);
		//前台穿过来的车间名称
		List<String> workshopList=jsonArray.subList(0, jsonArray.size());
		//得到合并后的车间
		List<String> list=new ArrayList<String>();
		list.addAll(workshopList);
		for(String str:workshopList) {
			List<String> magerList=orderProcedureTemplateMapper.getMergeToWorkShop(str);
			if(magerList!=null && magerList.size()>0) {
				list.addAll(magerList);
			}
		}
		//遍历
		for(String str:list) {
			map.put("tempWork", str);
			List<String> aleryHaveWorkProcedureList=orderProcedureTemplateMapper.getAleryHaveWorkProcedureList(map);
			if(aleryHaveWorkProcedureList !=null && aleryHaveWorkProcedureList.size()>0) {
				WorkshopProductionCycleBean wx=basicDataService.getWCById(str);
				if(wx==null) {
					throw new ServiceException("有车间已禁用");
				}else {
					throw new ServiceException(wx.getWorkshopName()+"车间在此订单中已存在，不可添加模板");
				}
			}
		}
		map.put("workshopList", list);
		List<ProcessBean> proceList=orderProcedureTemplateMapper.getProcess(map);
		for(int i=0;i<proceList.size();i++) {
			proceList.get(i).setId(StringUtil.getUUID());
		}
		map.put("procedureList", proceList);
		orderProcedureTemplateMapper.addOrderProcedure(map);
	}
	//获取模板数据
	public DatatablesViewPageBean getOrderProcedure(Map map) {
		List<String> tempIdList=orderProcedureTemplateMapper.getTempId(map);
		int count=orderProcedureTemplateMapper.getTempIdCount(map);
		DatatablesViewPageBean<OrderProcedureTemplateBean> dtcpb=new DatatablesViewPageBean<OrderProcedureTemplateBean>();
		dtcpb.setReturnData(orderProcedureTemplateMapper.getOrderProcedureTemplateDate(tempIdList));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	//删除模板
	public void deleteTemplate(Map map) {
		orderProcedureTemplateMapper.deleteTemplate(map);	
	}

//	获取人员工序
	public DatatablesViewPageBean getUserProcedure(Map map) {
		List<String> tempIdList=orderProcedureTemplateMapper.getUserId(map);
		int count=orderProcedureTemplateMapper.getUserIdCount(map);
		DatatablesViewPageBean<OrderProcedureTemplateBean> dtcpb=new DatatablesViewPageBean<OrderProcedureTemplateBean>();
		if(tempIdList.size() > 0 ) {
			dtcpb.setReturnData(orderProcedureTemplateMapper.getuserrProcedureDate(tempIdList));
		}else {
			dtcpb.setReturnData(new ArrayList<OrderProcedureTemplateBean>());
		}
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

//	获取订单实际报工工序
	public DatatablesViewPageBean getOrderRealProcedure(Map map) {
		String orderId=map.get("orderId").toString();
		List<String> orderIdList=orderProcedureTemplateMapper.getOrderId(map);
		int count=orderProcedureTemplateMapper.getOrderIdCount(map);
		if(orderIdList.size()<=0) {
			orderIdList.add(orderId);
		}
	    map.put("orderIdList", orderIdList);
       //获取返回的数据(订单实际工序)
		List<OrderProcedureTemplateBean> returnList=orderProcedureTemplateMapper.getOrderRealProcedureDate(map);
		
		
		Map mm=new HashMap();
		//遍历订单
		for(OrderProcedureTemplateBean oo :returnList) {
			mm.put("orderId", oo.getName());
			mm.put("loginCompany", map.get("loginCompany").toString());
			//遍历此订单车间
			List<WorkshopProductionCycleBean> cycleList=oo.getWorkShopList();
		    oo.setWorkShopList(this.getIsFinishReportWorkshop(cycleList,mm));
		}
		DatatablesViewPageBean<OrderProcedureTemplateBean> dtcpb=new DatatablesViewPageBean<OrderProcedureTemplateBean>();
		dtcpb.setReturnData(returnList);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}
	
	//获取报工整理车间
	public List<WorkshopProductionCycleBean> getIsFinishReportWorkshop(List<WorkshopProductionCycleBean> cycleList,
			Map mm) {
		for(WorkshopProductionCycleBean cc:cycleList) {
			mm.put("workShopId", cc.getId());
			//判断在此车间是否报过工
			List<ProcessBean> proList=orderProcedureTemplateMapper.getAleradyProcedure(mm);
            //如果有
			if(proList!=null && proList.size()>0) {
				this.setProcedureFinish(proList,cc.getProcessList(),mm);
			}
		}
		return cycleList;
	}
	
	
	/**
	 * @param proList 订单报工情况
	 * @param processList  车间实际工序
	 * @param mm 
	 */
	private void setProcedureFinish(List<ProcessBean> proList, List<ProcessBean> processList, Map mm) {
		//工序报工合格数满足订单数的物料
		List<ProcessBean> filterList=null;
		List<OrderInfoDetailBean> detaiList=putOutServiceNew.getOrderInfoDetail(mm);
		
		//交接入库的信息
//		List<ProcessBean> inFilter=filterList=proList.stream().filter(processBean ->processBean.getProcessName().equals("交接入库")).collect(Collectors.toList());
		for(ProcessBean pp:proList) {
		    if("交接至客户".equals(pp.getProcessName()) || "交接出库".equals(pp.getProcessName())) {
		        filterList=proList.stream().filter(processBean ->(processBean.getProcessName().equals("交接出库") || processBean.getProcessName().equals("交接至客户")) &&
		        		processBean.getQualityCount()>=processBean.getOrderCount()
		        		 ).collect(Collectors.toList());
			}else {
				filterList=proList.stream().filter(processBean ->processBean.getId().equals(pp.getId()) && processBean.getQualityCount()>=processBean.getOrderCount()).collect(Collectors.toList());
			}
		    Set<String> materialTypeSet=filterList.stream().map(ProcessBean::getMaching).collect(Collectors.toSet());
		    boolean bool=true;
		    //遍历本工序生产所有的物料
		    for(String materialType:materialTypeSet) {
		    	//获取此物料报工行数
		    	Set<String> reportRowIndexSet=filterList.stream().filter(report->report.getMaching().equals(materialType)).map(ProcessBean::getRowIndex).collect(Collectors.toSet());
		    	Set<String> detailRowIndexSet=detaiList.stream().filter(detail->detail.getMaterialType().equals(materialType)).map(OrderInfoDetailBean::getLineNo).collect(Collectors.toSet());
		        //如果报工行小于明细行
		    	if(reportRowIndexSet.size()<detailRowIndexSet.size()) {
		    		bool=false;
		    		break;
		    	}
		    }
		    if(filterList.size()<=0) {
		    	 bool=false;
		    }
	        if(bool) {
	        	this.setProcessReport(pp,processList,1);
	        }else {//如果出库数大于订单数的条数没有达到入库条数
	        	this.setProcessReport(pp,processList,2);
	        }
		}
	}

	/**
	 * 设置工序完成未完成
	 * @param pp
	 * @param processList
	 * @param i
	 */
	private void setProcessReport(ProcessBean pp, List<ProcessBean> processList, int i) {
		for(ProcessBean xx:processList) {
			if(pp.getId().equals(xx.getId())) {
					xx.setIsReport(i);
				break;
			}
		}
	}

//	//获取订单是否生产
//	public List<ProcessBean> getAleradyProcedure(Map map){
//		return orderProcedureTemplateMapper.getAleradyProcedure(map);
//	}

	//获取订单工序报工情况
	public List<WorkshopProductionCycleBean> getAleradyReportProcedure(Map map) {
		List<WorkshopProductionCycleBean> returnList=new ArrayList<WorkshopProductionCycleBean>();
		List<String> orderIdList=new ArrayList<String>();
		orderIdList.add(map.get("orderId").toString());
		map.put("orderIdList", orderIdList);
		//获取订单设置工序    工序默认未报工
		List<OrderProcedureTemplateBean> tempList=orderProcedureTemplateMapper.getOrderTreeData(map);
		//获取订单设置工序    工序默认未报工
		if(tempList == null || tempList.size()<=0) {
			tempList=orderProcedureTemplateMapper.getOrderRealProcedureDate(map);
		}
        //如果有设置，查询设置工序生产情况
		if(tempList != null && tempList.size()>0) {
			OrderProcedureTemplateBean orderProcedure=tempList.get(0);
			//获取车间信息
			returnList=orderProcedure.getWorkShopList();
			if(returnList==null || returnList.size()<=0) {
				returnList=orderProcedureTemplateMapper.getAleradyWorkshopProcedure(map);
			}
		}else {//如果没有设置   工序默认完全报工
			returnList=orderProcedureTemplateMapper.getAleradyWorkshopProcedure(map);
		}
		returnList=this.getIsFinishReportWorkshop(returnList, map);
		return returnList;
	}
	

//	获取所有模板信息
	public List<OrderProcedureTemplateBean> getAllTemp(Map map) {
		return orderProcedureTemplateMapper.getAllTemp(map);
	}
	
	//获取用户的工序
	public List<ProcessBean> getUserProcedureByUserId(Map map){
		return orderProcedureTemplateMapper.getUserProcedure(map);
	}
	//获取订单的工序
	public List<ProcessBean> getOrderProcess(Map map){
		return orderProcedureTemplateMapper.getOrderProcess(map);
	}
	

    //获取报工车间
	public List<WorkshopProductionCycleBean> getReportWorkShop(Map map) {
		List<WorkshopProductionCycleBean> returnList=new ArrayList<WorkshopProductionCycleBean>();
        //获取订单车间
		//获取订单结构数车间
		List<WorkshopProductionCycleBean> orderWorkShop=orderProcedureTemplateMapper.getOrderTreeWorkShop(map);
		if(orderWorkShop == null || orderWorkShop.size()<=0) {
			//订单工序车间
			orderWorkShop=orderProcedureTemplateMapper.getOrderWorkShop(map);
		}
		//获取用户车间
		List<WorkshopProductionCycleBean> userWorkShop=orderProcedureTemplateMapper.getUserWorkShop(map);
		
       //订单没有设置工序,人员设置了工序,返回用户的车间
		if((null==orderWorkShop || orderWorkShop.size()<=0) && (null!=userWorkShop && userWorkShop.size()>0)) {
			returnList=userWorkShop;
		}
		//人员没有设置工序，订单设置了工序,返回订单的车间
		if((null!=orderWorkShop && orderWorkShop.size()>0) && (null==userWorkShop || userWorkShop.size()<=0)) {
			returnList=orderWorkShop;
		}
		//订单与人员都设置了工序，返回合并车间
		if((null!=orderWorkShop && orderWorkShop.size()>0) && (null!=userWorkShop && userWorkShop.size()>0)){
			for(WorkshopProductionCycleBean order:orderWorkShop) {
				for(WorkshopProductionCycleBean user:userWorkShop) {
					if(order.getId().equals(user.getId())) {
						returnList.add(user);
						break;
					}
				}
			}
		}
		//订单与人员都没有设置，返回默认车间
		if((null==orderWorkShop || orderWorkShop.size()<=0) && (null==userWorkShop || userWorkShop.size()<=0)) {
			returnList=basicDataService.getWorkshop(map);
		}
		return returnList;
	}
	
	
	//获取报工车间
	public List<WorkshopProductionCycleBean> getInWorkShop(Map map) {
		List<WorkshopProductionCycleBean> returnList=new ArrayList<WorkshopProductionCycleBean>();
		//获取订单结构数车间
		List<WorkshopProductionCycleBean> orderWorkShop=orderProcedureTemplateMapper.getOrderTreeWorkShop(map);
		if(orderWorkShop == null || orderWorkShop.size()<=0) {
			//订单工序车间
			orderWorkShop=orderProcedureTemplateMapper.getOrderWorkShop(map);
		}
		//订单与人员都没有设置，返回默认车间
		if((null==orderWorkShop || orderWorkShop.size()<=0)) {
			returnList=basicDataService.getWorkshop(map);
		}else {
			returnList=orderWorkShop;
		}
		return returnList;
	}
	
	
	
	
    //获取报工车间
	public List<ProcessBean> getReportProcedure(Map map) {
		List<ProcessBean> proceList=new ArrayList<ProcessBean>();
		 //获取订单工序
		List<ProcessBean> orderProceList=orderProcedureTemplateMapper.getTreeProcess(map);
		if(null == orderProceList || orderProceList.size()<=0) {
			orderProceList=orderProcedureTemplateMapper.getOrderProcess(map);
		}
		//获取人员车间
		List<ProcessBean> userProceList=orderProcedureTemplateMapper.getUserProcedure(map);
		//如果订单没有设置工序,人员设置了工序，返回人员工序
		if((null==orderProceList || orderProceList.size()<=0) && (null!=userProceList && userProceList.size()>0)) {
			proceList=userProceList;
		}
		//如果订单设置了，人员没有设置，返回订单
		if((null!=orderProceList && orderProceList.size()>0) && (null==userProceList || userProceList.size()<=0)) {
			proceList=orderProceList;
		}
		//如果订单与人员都设置了工序，返回合并
        if((null !=orderProceList && orderProceList.size()>0) && (null!=userProceList && userProceList.size()>0)) {
        	for(ProcessBean order:orderProceList) {
        		for(ProcessBean user:userProceList) {
        			if(user.getId().equals(order.getId())) {
        				proceList.add(order);
            			break;
        			}
        		}
        	}
//        	proceList=orderProceList;
//        	proceList=orderProcedureTemplateMapper.getReportProcedure(map);
		}
        //都没有设置，返回默认
        if((null==orderProceList || orderProceList.size()<=0) && (null==userProceList || userProceList.size()<=0)) {
        	proceList=basicDataService.getWorkingProcedureByWorkId(map);
        }
        DepartmentBean departmentBean=orderProcedureTemplateMapper.getDeptInWorkShopMode(map);
        //如果公司设定只能领料入库
        if(departmentBean.getInWorkShopMode()==1) {
        	for(ProcessBean pp:proceList) {
        		if(pp.getProcessName().equals("交接入库")) {
        			proceList.remove(pp);
        			break;
        		}
        	}
        }
		return proceList;
	}

	//移除模板工序
	public void removeTemplateProcedure(Map map) {
		orderProcedureTemplateMapper.removeTemplateProcedure(map);		
	}

    //获取模板已有工序
	public List<ProcessBean> getTemolateProcess(Map map) {
		return orderProcedureTemplateMapper.getTemolateProcess(map);		
	}

	//移除用户工序
	public void removeUserProcedure(Map map) {
		orderProcedureTemplateMapper.removeUserProcedure(map);		
	}

	//修改模板名称
	public void updateTempName(Map map) {
		orderProcedureTemplateMapper.updateTempName(map);
	}

	//获取订单工序详情
	public List<OrderProcedureTemplateBean> getOrderProcedureDetail(Map map,String orderId) {
		List<String> list=new ArrayList<String>();
		list.add(orderId);
		map.put("orderIdList", list);
		return orderProcedureTemplateMapper.getOrderRealProcedureDate(map);
	}
	
	//获取订单已有工序详情
	public List<ProcessBean> getOrderHaveProcedure(Map map) {
		return orderProcedureTemplateMapper.getOrderHaveProcedure(map);
	}

	//创建订单工序表格
		public File createExcle(String tempFolder, String orderId,Map map) throws ServiceException {
		    OrderProcedureTemplateBean orderProcedureTemplateBean=this.getOrderProcedureDetail(map,orderId).get(0);
		    List<OrderBean> orderBeanList=orderService.getOrderDetail(map);
		    OrderBean orderBean=orderBeanList.get(0);
	        //获取需要显示的订单信息
		    OrderBean order=orderProcedureTemplateMapper.getOrder(orderId);
		    order.setFeedCount(orderProcedureTemplateMapper.getFeedCount(orderId));
//		    List<TypeColorBean> listType=orderProcedureTemplateMapper.getOrderDetail(orderId);
		    List<WorkshopProductionCycleBean> wpcbList=orderProcedureTemplateBean.getWorkShopList();
		    wpcbList=this.mergeWorkList(wpcbList,orderBean.getOrderId());
		    File outFile= new File(tempFolder, UUID.randomUUID().toString() + ".xlsx");
			if(!outFile.getParentFile().exists()){
				outFile.getParentFile().mkdirs();
			}
			Workbook wb;
			OutputStream fos = null;
			try {
				wb = new XSSFWorkbook();
				Sheet sheet = wb.createSheet();
				
				
				
				
				
				int rowIndex = 0;
				int colIndex=0;
				Row headRow;
				Cell cell;
				headRow=sheet.createRow(rowIndex);
				cell = headRow.createCell(colIndex);
				cell.setCellValue("订单编号 : ");
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue(order.getCustomerOrderId());
				colIndex++;
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue("厂号 ： ");
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue(order.getFactoryId());
				colIndex++;
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue("交期 ： ");
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue(order.getJiaoDate());
				colIndex++;
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue("订单数 ： ");
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue(order.getOrderCount());
				colIndex++;
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue("投料数 ： ");
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue(order.getFeedCount());
				colIndex++;
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue("客号 ： ");
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue(order.getCustomerId());
				colIndex++;
				colIndex++;
				cell = headRow.createCell(colIndex);
				cell.setCellValue("尺寸 ： ");
				rowIndex++;
				colIndex=0;
				
//				int colorRowIndex=rowIndex;
//				for(int j=0;j<listType.size();j++) {
//					rowIndex=colorRowIndex;
//					if(j==0) {
//						headRow=sheet.createRow(rowIndex);
//					}else {
//						headRow=sheet.getRow(rowIndex);
//					}
//					cell = headRow.createCell(colIndex);
//					cell.setCellValue(listType.get(j).getMaterialType()+"色");
//					int colorColIndex=colIndex;
//					colIndex++;
//					cell = headRow.createCell(colIndex);
//					cell.setCellValue(listType.get(j).getMaterialType()+"色号");
//					colIndex++;
//					cell = headRow.createCell(colIndex);
//					cell.setCellValue("每条料可开数/付");
//					colIndex++;
//					cell = headRow.createCell(colIndex);
//					cell.setCellValue("开料方式");
//					colIndex++;
//					cell = headRow.createCell(colIndex);
//					cell.setCellValue("用料数/条");
//					colIndex++;
//					cell = headRow.createCell(colIndex);
//					cell.setCellValue("圈料开料尺寸");
//					colIndex++;
//					
//					List<OrderDeatilBean> listDetail=listType.get(j).getListDetail();
//					for(int z=0;z<listDetail.size();z++) {
//						rowIndex++;
//						int xx=colorColIndex;
//						if(xx==0) {
//							headRow=sheet.createRow(rowIndex);
//						}
//						cell = headRow.createCell(xx);
//						cell.setCellValue(listDetail.get(z).getColorDescription());
//						xx++;
//						cell = headRow.createCell(xx);
//						cell.setCellValue(listDetail.get(z).getColor());
//					}
//				}
				
				
//				//创建描述行
//				headRow=sheet.createRow(rowIndex);
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("圈色");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("圈色描述");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("每条料可开数/付");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("开料方式");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("用料数/条");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("圈料开料尺寸");
//				colIndex++;
//				
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("脾色");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("色号");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("每条料可开数/付");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("开料方式");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("用料数/条");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("脾料开料尺寸");
//				colIndex++;
//				
//				
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("金属框色描述");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("金属框色色号");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("金属脚色描述");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("金属脚色色号");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("金属饰片描述");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("金属饰片色号");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("配件描述");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("烫印色");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("点漆色");
//				colIndex++;
//				cell = headRow.createCell(colIndex);
//				cell.setCellValue("水晶胶色");
				
////				int length=listDetail.size();
//				rowIndex++;
//				
////				for(int j=0;j<length;j++) {
////					headRow=sheet.createRow(rowIndex);
////					colIndex=0;
////					cell=headRow.createCell(colIndex);
////					cell.setCellValue(listDetail.get(j).getQuanSeMiao());
////					colIndex++;
////					cell=headRow.createCell(colIndex);
////					cell.setCellValue(listDetail.get(j).getQuanSe());
////					colIndex++;
////					colIndex++;
////					colIndex++;
////					colIndex++;
////					if(j==0) {
////						CellRangeAddress callRange3 = new CellRangeAddress(rowIndex,rowIndex+length-1,colIndex,colIndex);//起始行,结束行,起始列,结束列  
////						sheet.addMergedRegion(callRange3);
////					}
////					colIndex++;
////					
////					cell=headRow.createCell(colIndex);
////					cell.setCellValue(listDetail.get(j).getBiSeMiao());
////					colIndex++;
////					cell=headRow.createCell(colIndex);
////					cell.setCellValue(listDetail.get(j).getBiSe());
////					colIndex++;
////					colIndex++;
////					colIndex++;
////					colIndex++;
////					if(j==0) {
////						CellRangeAddress callRange2 = new CellRangeAddress(rowIndex,rowIndex+length-1,colIndex,colIndex);//起始行,结束行,起始列,结束列  
////						sheet.addMergedRegion(callRange2);
////					}
////					colIndex++;
////					
////					cell=headRow.createCell(colIndex);
////					cell.setCellValue(listDetail.get(j).getJinQuanSeMiao());
////					colIndex++;
////					cell=headRow.createCell(colIndex);
////					cell.setCellValue(listDetail.get(j).getJinQuanSe());
////					colIndex++;
////					cell=headRow.createCell(colIndex);
////					cell.setCellValue(listDetail.get(j).getJinBiSeMiao());
////					colIndex++;
////					cell=headRow.createCell(colIndex);
////					cell.setCellValue(listDetail.get(j).getJinBiSe());
////					colIndex++;
////					rowIndex++;
////				}
////				rowIndex++;
//				
				
				
				
				rowIndex=rowIndex+2;
				colIndex=0;
				headRow=sheet.createRow(rowIndex);
				for(WorkshopProductionCycleBean ss:wpcbList){
					rowIndex=6;
					
					//创建合并单元格
					int endColIndex=colIndex;
					CellRangeAddress callRange1 = new CellRangeAddress(rowIndex,rowIndex,colIndex,colIndex+4);//起始行,结束行,起始列,结束列  
					sheet.addMergedRegion(callRange1);
					Row rowx=null;
					if(colIndex==0) {
						rowx=sheet.createRow(rowIndex);
					}else {
						rowx=sheet.getRow(rowIndex);
					}
					cell = rowx.createCell(endColIndex);
					cell.setCellValue(ss.getWorkshopName());
					rowx.setHeightInPoints(30);
					rowIndex++;
					
					//创建工序行
					if(colIndex==0) {
						rowx=sheet.createRow(rowIndex);
					}else {
						rowx=sheet.getRow(rowIndex);
					}
					rowx.setHeightInPoints(25);
					cell = rowx.createCell(endColIndex);
					cell.setCellValue("产品编码");
					endColIndex++;
					cell = rowx.createCell(endColIndex);
					cell.setCellValue("数量");
					endColIndex++;
					cell = rowx.createCell(endColIndex);
					cell.setCellValue("操作人");
					endColIndex++;
					cell = rowx.createCell(endColIndex);
					cell.setCellValue("部门");
					endColIndex++;
					cell = rowx.createCell(endColIndex);
					cell.setCellValue("特别说明");
					endColIndex++;
					
					
					
					
					
					
					List<ProcessBean> processList=ss.getProcessList();
					rowIndex=8;
					for(ProcessBean processBean:processList) {
						Row row=sheet.getRow(rowIndex);
						if(row==null) {
							row=sheet.createRow(rowIndex);
						}
						cell = row.createCell(colIndex);
						cell.setCellValue(processBean.getProcessName());
						rowIndex++;
					}
					colIndex=endColIndex+1;
				}
				fos = new FileOutputStream(outFile);
				wb.write(fos);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			}finally {
				try {
					if (null != fos)
						fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return outFile;
		}
	
	

	//移除订单工序
	public void removeOrderProcedure(Map map) throws ServiceException {
		List<String> listStr=workshopService.findOrderProcedureRepoortRecore(map);
		if(listStr != null && listStr.size()>0) {
			throw new ServiceException("此订单此工序已报工，不可删除");
		}
		orderProcedureTemplateMapper.removeOrderProcedure(map);
	}

	 //合并车间转换
	public List<WorkshopProductionCycleBean> mergeWorkList(List<WorkshopProductionCycleBean> wpcbList,String orderId) {
		List<WorkshopProductionCycleBean> xx=new ArrayList<WorkshopProductionCycleBean>();
		for(WorkshopProductionCycleBean dd:wpcbList) {
			//获取合并的id集合
			List<String> mergeIdList=orderProcedureTemplateMapper.getMergeToWorkShop(dd.getId());
            //如果此车间含有合并车间
			if(mergeIdList !=null && mergeIdList.size()>0) {
				mergeIdList.add(dd.getId());//奖此车间值也加入查询序列
				List<ProcessBean> processList=orderProcedureTemplateMapper.getMergeProcessBean(mergeIdList,orderId);
				dd.setProcessList(processList);
				xx.add(dd);
			}else {
				//查询此车间是否被合并
				mergeIdList=orderProcedureTemplateMapper.getMergeWorkShop(dd.getId());
				if(mergeIdList==null || mergeIdList.size()<=0) {
					xx.add(dd);
				}
			}
		}
		return xx;
	}

	//获取本车间的合并车间
	public List<String> getMerge(String id){
		return orderProcedureTemplateMapper.getMergeWorkShop(id);
	}
	
	
	//获取本车间的被合并车间
	public List<String> getMergeToWorkShop(String id){
		return orderProcedureTemplateMapper.getMergeToWorkShop(id);
	}
	
	//获取订单主要信息
	public OrderBean getOrderMain(Map map,String orderId) {
		OrderBean order=orderProcedureTemplateMapper.getOrder(orderId);
	    order.setFeedCount(orderProcedureTemplateMapper.getFeedCount(orderId));
	    return order;
	}

	//获取订单物料详情
	public List<OrderBoLiangBean> getMaterialDetail(Map map, String orderId) {
		 return orderProcedureTemplateMapper.getOrderDetail(orderId);
	}

	//获取合并车间的实际报工工序s
	public List<WorkshopProductionCycleBean> orderMagerProcedure(Map map, String orderId) {
		List<OrderProcedureTemplateBean> list=this.getOrderProcedureDetail(map,orderId);
		List<WorkshopProductionCycleBean> wpcbList=new ArrayList<WorkshopProductionCycleBean>();
		if(null != list && list.size()>0) {
			OrderProcedureTemplateBean	orderProcedureTemplateBean=this.getOrderProcedureDetail(map,orderId).get(0);
		    wpcbList=orderProcedureTemplateBean.getWorkShopList();
			wpcbList=this.mergeWorkList(wpcbList,orderId);
		}
		for(WorkshopProductionCycleBean wpcb:wpcbList) {
			Map paramMap=new HashMap();
			paramMap.put("orderId", map.get("orderId"));
			String workType=workshopService.geReportObjectByWorkShopId(wpcb.getId());//车间设置的加工对象
			//如果车间设置加工了对象
			String[] workTypeList2=null;
			if(workType!=null && !"".equals(workType)) {
				//如果设置了加工对象
			    workTypeList2=workType.split(",");
				int index = Arrays.binarySearch(workTypeList2,"整架");
				//如果加工对象不包含整架
				if(index<0) {
					paramMap.put("workTypeList", workTypeList2);
				}
			}
			wpcb.setColorList(orderProcedureTemplateMapper.getOrderWorkColor(paramMap));
		}
	    return wpcbList;
	}

	//获取订单工序报工数据
	public List<ReportBean> getProcedureReport(Map map) {
		return orderProcedureTemplateMapper.getProcedureReport(map);
	}

	//设置订单排序
	public void setOrderSort(Map map) {
		 OrderBean order=orderService.getOrderByOrderId(map.get("orderId").toString());
		 map.put("orderSort", order.getSort());
		 Integer sort=Integer.parseInt(map.get("sort").toString());
		 if(sort<0) {//如果是设置生产完成
			 Set<ReportBean> notApprovalMessage=orderProcedureTemplateMapper.getNotApprovalMessage(map.get("orderId").toString());
		     if(null!= notApprovalMessage && notApprovalMessage.size() > 0) {
		    	 Map approvalMap=new HashMap();
		    	 approvalMap.put("loginCompany", map.get("loignCompany"));
		    	 notApprovalMessage=this.setCanApprovalUser(notApprovalMessage,approvalMap);
		    	 JSONArray jsonArray=JSONArray.fromObject(notApprovalMessage);
		    	 Assert.notNull(null,jsonArray.toString());
		     }
			 int type=0;
			 if(null!=map.get("type") && !"".equals(map.get("type"))) {
				 type=Integer.parseInt(map.get("type").toString());
			 }
		     if(type==2) {
		    	 map.put("sort", -3);
		    	 this.insertIntoFinishRecord(order,map);
		     }
		     //设置订单完成
		     orderService.updateOrderSortByFinish(map);
		 }else {
			 if(order.getSort()>sort) {
				 //向前改排序
				 orderService.updateOrderSortBrfore(map);
			 }else {
				 orderService.updateOrderSortAfter(map);
			 }
		 }
	}

	/**
	 * 设置订单未审核的可审核人
	 * @param notApprovalMessage
	 * @param approvalMap 
	 * @return
	 */
	private Set<ReportBean> setCanApprovalUser(Set<ReportBean> notApprovalMessage, Map approvalMap) {
		notApprovalMessage.forEach(report->{
			if(0==report.getType()) {
				approvalMap.put("processId", report.getProcedur());
				approvalMap.put("workShopId", report.getWorkShopName());
				report.setApprovalUserName(workshopService.getCanApprovalReportUser(approvalMap));
			}else {
				approvalMap.put("type", report.getType());
				approvalMap.put("loginUserId", report.getTouchPeople());
				report.setApprovalUserName(approvalService.getApprovalUserBeanByLoginUserId(approvalMap));
			}
		});
		return notApprovalMessage;
	}

	/**
	 * 如果是设备厂,设置完成的时候需要插入成品入库记录
	 * @param order
	 * @param map
	 */
	private void insertIntoFinishRecord(OrderBean order, Map map) {
		Assert.isTrue(order.getOrderCount()==1,"订单数不为1,不可结单");
	    //校验订单物料是否领完
		this.checkAllMaterislIsReceive(order.getOrderId());
		List<WarehouseInOutDetailBean> inOutList=new ArrayList<WarehouseInOutDetailBean>();
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		WarehouseInOutDetailBean otherWarehouseBean=new WarehouseInOutDetailBean();
		otherWarehouseBean.setId(CreateIdUtil.getId(map.get("loginCompany").toString()+"成品仓"));
		otherWarehouseBean.setCreateTime(simpleDateFormat.format(new Date()));
		otherWarehouseBean.setCreateUser(map.get("loginUserId").toString());
		otherWarehouseBean.setStatus(0);
		otherWarehouseBean.setCompany(map.get("loginCompany").toString());
		otherWarehouseBean.setRemark("结单");
		otherWarehouseBean.setInOutUnit("台");
		otherWarehouseBean.setRowIndex("-1");
		otherWarehouseBean.setWarehouseType(1);
		otherWarehouseBean.setSource(3);
		otherWarehouseBean.setOrderId(order.getOrderId());
		otherWarehouseBean.setCount(1.0);
		otherWarehouseBean.setNoCount(0.0);
		otherWarehouseBean.setType(11);
		inOutList.add(otherWarehouseBean);
		StringBuilder weiXinNeiRong =new StringBuilder("");
		weiXinNeiRong.append("物料类型:").append("订单成品").append("\n")
        .append("订单编号:").append(order.getCompanyOrderId()).append("\n")
		.append("工厂型号:").append(order.getFactoryId()).append("\n")
		.append("来源:").append("生产结单").append("\n")
		.append("数量:").append("1").append("\n");
		String idS="?ids=";
		for(WarehouseInOutDetailBean cc:inOutList) {
			idS=idS+cc.getId()+",";
		}
		idS=idS.substring(0, idS.length()-1);
		companyMaterialService.insertInOutRecode(inOutList);
		Map paramMap=new HashMap();
		paramMap.put("loginUserId", map.get("loginUserId"));
		paramMap.put("loginCompany", map.get("loginCompany"));
		paramMap.put("loginUserName", map.get("loginUserName"));
		String returnErrorStr=companyMaterialService.sendWechatMessage("有新的物料入库，请尽快审核", 2, weiXinNeiRong.toString(), simpleDateFormat.format(new Date()), paramMap, RedirectUrlUtil.queryWarehouse+idS, 1);
	}

	/**
	 * 校验订单物料是是否领完
	 * @param orderId
	 */
	private void checkAllMaterislIsReceive(String orderId) {
          List<FeedOrderDetailBean> list=orderProcedureTemplateMapper.getOrderNotReceiveMaterial(orderId);
          if(list != null && list.size()>0) {
        	  Set<String> materialNameSet=list.stream().map(FeedOrderDetailBean::getMaterialName).collect(Collectors.toSet());
              Assert.notNull(null,"该订单"+materialNameSet.toString()+"未领料,不可结单");
          }
	}

	//保存打印详情
	public void savePrintDetail(Map map) {
         String json=map.get("printDetailArray").toString();
         JSONArray jsonArray=JSONArray.fromObject(json);
         List<PrintDetailBean> detailList=(List<PrintDetailBean>) JSONArray.toCollection(jsonArray, PrintDetailBean.class);
         if(detailList!=null && detailList.size()>0) {
        	 orderProcedureTemplateMapper.deletePrientDetail(map);
        	 map.put("detailList", detailList);
        	 orderProcedureTemplateMapper.insertPrientDetail(map);
         }
	}

	//获取模板车间
	public List<WorkshopProductionCycleBean> getTempWorkShop(Map map) {
		return orderProcedureTemplateMapper.getTempWorkShop(map);
	}
	
	//将订单工序另存为模板
	public void saveTemplateByOrderProcedure(Map map) {
		String uuid=StringUtil.getUUID();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String createTime = formatter.format(new Date());
		List<ProcessBean> list= orderProcedureTemplateMapper.getOrderFomrtProcess(map);
		for(int i=0;i<list.size();i++) {
			list.get(i).setId(StringUtil.getUUID());
		}
		map.put("procedureArray", list);
		map.put("uuid", uuid);
		map.put("createTime", createTime);
		orderProcedureTemplateMapper.insertTemplate(map);
		orderProcedureTemplateMapper.insertTemplateProcedure(map);
	}

	/**
	 * 获取订单下一道工序
	 * orderId 订单编号
	 * procedureId 工序id
	 * materialType 可能不传
	 * @param map
	 * @return
	 */
	public ProcessBean getNextProcedureName(Map map) {
		ProcessBean processBean=orderProcedureTemplateMapper.getTreeProcessByProcedureId(map);
		ProcessBean netxProce = null;
		if(processBean != null) {
			netxProce=orderProcedureTemplateMapper.getNextProcedureByProcessBean(processBean);
		}else {
			netxProce=orderProcedureTemplateMapper.getNextProcedureFromSet(map);
		}
		return netxProce;
	}
	
}
